<template>
  <div class="login">
    <div class="login-wrap">
      <!-- 表单头 -->
      <ul class="menu-tab">
        <li
          :class="{ current: isActive == index }"
          v-for="(item, index) in menuTab"
          :key="item.id"
          @click="toggleMenu(index)"
        >{{ item.txt }}</li>
      </ul>
      <!-- 用户登录表单 -->
      <el-form :model="ruleForm" status-icon :rules="rules" ref="loginForm" class="login-form">
        <el-form-item prop="username" class="item-form">
          <label for="username">邮箱</label>
          <el-input id="username" type="text" v-model="ruleForm.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="password" class="item-form">
          <label for="password">密码</label>
          <el-input
            id="password"
            type="password"
            v-model="ruleForm.password"
            autocomplete="off"
            maxlength="20"
            minlength="6"
          ></el-input>
        </el-form-item>
        <el-form-item v-show="isActive == 1" prop="passwords" class="item-form">
          <label for="passwords">确认密码</label>
          <el-input
            id="passwords"
            type="password"
            v-model="ruleForm.passwords"
            autocomplete="off"
            maxlength="20"
            minlength="6"
          ></el-input>
        </el-form-item>
        <el-form-item prop="code" class="item-form">
          <label for="code">验证码</label>
          <el-row :gutter="10">
            <el-col :span="16">
              <el-input id="code" v-model="ruleForm.code" maxlength="6" minlength="6"></el-input>
            </el-col>
            <el-col :span="8">
              <el-button
                type="success"
                class="btn"
                @click="getSms()"
                :disabled="codeButtonStatus.status"
              >{{ codeButtonStatus.text }}</el-button>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item>
          <el-button
            type="danger"
            :disabled="loginButtonStatus"
            class="btn btn1"
            @click="submitForm('loginForm')"
          >{{ isActive == 0 ? "登录" : "注册" }}</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import sha1 from "js-sha1";
import { GetSms, Register, Login } from "@/api/login";
import {
  stripscript,
  validateEmail,
  validatePass,
  validateCode
} from "@/utils/validate";
import { reactive, ref, onMounted } from "@vue/composition-api";
export default {
  setup(props, { refs, root }) {
    // 验证码验证
    let checkCode = (rule, value, callback) => {
      ruleForm.code = stripscript(value);
      value = ruleForm.code;
      if (value === "") {
        return callback(new Error("请输入验证码"));
      } else if (!validateCode(value)) {
        return callback(new Error("验证码格式错误"));
      } else {
        callback();
      }
    };
    // 用户名验证规则
    let validateUsername = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入用户名"));
      } else if (!validateEmail(value)) {
        callback(new Error("请输入正确邮箱格式"));
      } else {
        callback();
      }
    };
    // 密码验证规则
    let validatePassword = (rule, value, callback) => {
      ruleForm.password = stripscript(value);
      value = ruleForm.password;
      if (value === "") {
        callback(new Error("请请输入密码"));
      } else if (!validatePass(value)) {
        callback(new Error("请输入正确密码格式"));
      } else {
        callback();
      }
    };
    // 确认密码验证规则
    let validatePasswords = (rule, value, callback) => {
      if (isActive.value == 0) {
        callback();
      } else if (value === "") {
        callback(new Error("请请输入确认密码"));
      } else if (value != ruleForm.password) {
        callback(new Error("密码输入不一致"));
      } else {
        callback();
      }
    };
    /* 
    数据声明 
    *****************************************************************************/

    let isActive = ref(0); // 登录注册转态切换
    let loginButtonStatus = ref(true); // 提交按钮默认禁用
    const menuTab = reactive([{ txt: "登录" }, { txt: "注册" }]);
    let codeButtonStatus = reactive({ status: false, text: "验证码" }); // 验证码状态
    let timer = ref(null);
    // 表单数据
    let ruleForm = reactive({
      username: "233158114@qq.com",
      password: "1235assd",
      passwords: "1235assd",
      code: "sadasd"
    });
    // 表单验证
    const rules = reactive({
      username: [{ validator: validateUsername, trigger: "blur" }],
      password: [{ validator: validatePassword, trigger: "blur" }],
      passwords: [{ validator: validatePasswords, trigger: "blur" }],
      code: [{ validator: checkCode, trigger: "blur" }]
    });

    /* 声明函数
     **********************************************************************/
    // 登录注册表单切换
    const toggleMenu = index => {
      isActive.value = index;
      refs.loginForm.resetFields();
      clearCodeStatus(); // 清空验证码状态
    };

    // 单击获取验证码操作
    const getSms = () => {
      if (ruleForm.username == "") {
        root.$message.error("邮箱不能为空");
        return false;
      }
      if (!validateCode(ruleForm.username)) {
        root.$message.error("邮箱格式错误");
        return false;
      }
      // 点击后修改验证码状态
      codeButtonStatus.status = true;
      codeButtonStatus.text = "发送中";
      // 传递参数
      let requestData = {
        username: ruleForm.username,
        module: isActive.value == 0 ? "login" : "register"
      };
      // 发送验证码请求接口
      GetSms(requestData)
        .then(response => {
          let data = response.data;
          console.log(data);
          root.$message.success("验证码已发送");
          loginButtonStatus.value = false;
          countDown(60); // 定时器
        })
        .catch(error => {
          console.log(error);
        });
    };

    /*
    提交表单校验 
     */

    const submitForm = formName => {
      console.log(isActive.value);
      refs[formName].validate(valid => {
        // 表单验证通过
        if (valid) {
          // 判断提交的是登录还是注册
          isActive.value == 0 ? login() : register();
        } else {
          root.$message.error("请输入正确信息");
          return false;
        }
      });
    };

    /* 
    登录提交
    */
    const login = () => {
      let requestData = {
        username: ruleForm.username,
        password: sha1(ruleForm.password),
        code: ruleForm.code,
        module: "login"
      };
      root.$store
        .dispatch("app/LOGIN", requestData)
        .then(response => {
          root.$message.success("登录成功");
          root.$router.push("/console");
          console.log(response);
        })
        .catch(error => {
          console.log(error);
        });
    };

    /* 
   注册提交
   */
    const register = () => {
      let requestData = {
        username: ruleForm.username,
        password: sha1(ruleForm.password),
        code: ruleForm.code,
        module: "register"
      };
      Register(requestData)
        .then(response => {
          let data = response.data;
          root.$message.success(data.message); //注册成功
          toggleMenu(0);
        })
        .catch(error => {
          console.log(error);
        });
    };
    /* 
    验证码倒计时
    */
    const countDown = number => {
      if (timer.value) clearInterval(timer.value);
      timer.value = setInterval(() => {
        number--;
        codeButtonStatus.text = `倒计时${number}秒`;
        if (number == 0) {
          clearInterval(timer.value);
          codeButtonStatus.text = "再次发送";
          codeButtonStatus.status = false;
        }
      }, 1000);
    };

    /* 
    验证码倒计时
    */
    const clearCodeStatus = () => {
      codeButtonStatus.status = false;
      codeButtonStatus.text = "获取验证码";
      clearInterval(timer.value);
    };
    /* 生命周期 */
    // 挂载后
    onMounted(() => {});
    return {
      // 数据
      menuTab,
      isActive,
      ruleForm,
      rules,
      loginButtonStatus,
      codeButtonStatus,
      timer,
      // 函数
      toggleMenu,
      submitForm,
      getSms,
      clearCodeStatus
    };
  }
};
</script>

<style lang="scss" scoped>
* {
  margin: 0;
  padding: 0;
}
.login {
  height: 100vh;
  background-color: #aa5126;
}
.login-wrap {
  position: absolute;
  width: 330px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
.menu-tab {
  text-align: center;
  li {
    display: inline-block;
    width: 88px;
    list-style: none;
    line-height: 36px;
    font-size: 14px;
    color: #fff;
    border-radius: 2px;
    cursor: pointer;
  }
  .current {
    background-color: rgba(255, 222, 173, 0.3);
  }
}
.login-form {
  label {
    font-size: 14px;
    display: block;
    color: #fff;
    text-align: left;
    margin: 5px 0;
  }
  .item-form {
    margin-bottom: 13px;
  }
  .btn {
    display: block;
    width: 100%;
    height: 40px;
  }
  .btn1 {
    margin-top: 20px;
  }
}
</style
>>
